/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.michalwski.mpnotepad;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

/**
 *
 * @author Michal Piotrowski
 */
class NoteEditor extends TextBox implements CommandListener {
    private Command saveNoteCommand;
    private Command backCommand;
    private Command discardChangesCommand;
    
    private MPNotepad parent;
    
    private String name;
    private final String content;
    
    private Alert alert;
    
    
    public NoteEditor(MPNotepad parent) {
        this(parent, "", "");
    }
    
    public NoteEditor(MPNotepad parent, String name, String content) {
        super(name, content, 500, TextField.ANY);
        
        this.parent = parent;
        this.name = name;
        this.content = content;
        
        createCommands();
        
        
    }
    
    private void createCommands(){
        saveNoteCommand = new Command("Save", Command.OK, 0);
        backCommand = new Command("Back", Command.BACK, 0);
        discardChangesCommand = new Command("No", Command.CANCEL, 0);
        addCommand(backCommand);
        setCommandListener(this); 
    }

    public void commandAction(Command c, Displayable d) {
        if (d == this) {
            if (c == backCommand) {
                goBack();
            } 
        } else if (c == saveNoteCommand) {
                
        } else if (c == discardChangesCommand) {
            setString(this.content);
            if (d == alert) {
                goBack();
            }
        }
    }

    private void goBack() {
        if (content.equals(getString())){
            parent.switchDisplayable(null, parent.getStartScreen());
        } else {
            alert = new Alert("Changes", "Note changed. Save it?", null, AlertType.CONFIRMATION);
            alert.addCommand(saveNoteCommand);
            alert.addCommand(discardChangesCommand);
            alert.setCommandListener(this);
            parent.switchDisplayable(alert, this);
        }
    }

    
    
}
